const express = require("express");
const db = require("../../config/dbserver.js");
const router = express.Router();
const simdjson = require("simdjson");
const axios = require("axios");
const logger = require("../../utils/logger");

// 用于安全解析JSON的辅助函数
function parseJson(jsonString) {
  if (!jsonString) return null;
  try {
    if (simdjson.isValid(jsonString)) {
      return simdjson.parse(jsonString);
    }
    return JSON.parse(jsonString);
  } catch (_) {
    return null;
  }
}

// 发送标准化响应的辅助函数
function sendResponse(res, code, data, message = "success") {
  res.status(code).send({ code, data, message });
}

// 获取客户端IP（考虑代理）
function getClientIp(req) {
  const xfwd = req.headers && req.headers["x-forwarded-for"];
  if (xfwd && typeof xfwd === "string") {
    return xfwd.split(",")[0].trim();
  }
  return req.ip || (req.socket && req.socket.remoteAddress) || "";
}

// 获取初始数据
router.get("/", async (req, res) => {
  try {
    const dbData = await db.dbQuery("SELECT * FROM init");
    const data = dbData.length > 0 ? parseJson(dbData[0].data) || {} : {};
    sendResponse(res, 200, data);
  } catch (error) {
    logger.error(`获取初始数据时出错: ${error}`);
    sendResponse(res, 500, null, "Internal Server Error");
  }
});

// 设置初始数据
router.post("/set", async (req, res) => {
  try {
    const { data } = req.body;
    await db.dbQuery("UPDATE init SET data = ? WHERE id = 0", [
      JSON.stringify(data)
    ]);
    sendResponse(res, 200, {});
  } catch (error) {
    logger.error(`设置初始数据时出错: ${error}`);
    sendResponse(res, 500, null, "Internal Server Error");
  }
});

// 处理首次用户回调的中间件
async function handleFirstEnter(req, res, next) {
  const { oaid, firstEnter, platform, location } = req.body;
  // if (!oaid) {
  //   return sendResponse(res, 400, null, "缺少 oaid");
  // }
  const clientIp = getClientIp(req);
  const reqData = {
    platform: platform,
    location: location,
    enter: 1,
    track: 0,
    banner: 0,
    interstitial: 0,
    video: 0,
    data: {
      fake: {
        1: {
          enter: 1,
          time: new Date().toLocaleString(),
          num: { banner: 0, video: 0, interstitial: 0 }
        }
      }
    },
    error: {
      info: []
    }
  };

  // 首次进入时，先确保 log1 表中存在对应记录
  // 如果不存在，则创建一条记录
  const [existingLog1] = await db.dbQuery("SELECT * FROM log1 WHERE oaid = ?", [
    oaid
  ]);
  if (existingLog1) {
    reqData.platform = existingLog1.platform;
    reqData.location = existingLog1.location;
    reqData.enter = Number(existingLog1.enter) || 1;
    reqData.track = Number(existingLog1.track) || 0;
    reqData.banner = Number(existingLog1.banner) || 0;
    reqData.interstitial = Number(existingLog1.interstitial) || 0;
    reqData.video = Number(existingLog1.video) || 0;
    reqData.data = parseJson(existingLog1.data) || { fake: {} };
    reqData.error = parseJson(existingLog1.error) || { info: [] };
  } else {
    await db.dbQuery(
      "INSERT INTO log1 (oaid, platform, location, data, enter, track, create_at) VALUES (?, ?, ?, ?, ?, ?, now())",
      [
        oaid,
        platform,
        location,
        JSON.stringify(reqData.data),
        reqData.enter,
        reqData.track
      ]
    );
  }
  // 透传首进标识供下游使用
  reqData.firstEnter = Boolean(firstEnter);
  req.data = reqData;
  console.log("------------------");

  if (!firstEnter) {
    req.data = reqData;
    return next();
  }

  // 查询是否有监测回传的地址
  const dbDatas = await db.dbQuery("SELECT * FROM track WHERE oaid = ?", [
    oaid
  ]);
  // 没有精确回传地址就模糊回传
  // 秒级时间戳
  if (dbDatas.length) {
    console.log(dbDatas.length);
    console.log("检测地址回传执行 首次进入 ---------------------");
    await Promise.all(
      dbDatas.map(async (dbData) => {
        console.log("dbData", dbData.callbackurl);
        const timestamp = Math.floor(Date.now() / 1000);
        const isPrecise = Boolean(dbData?.callbackurl); // 是否是精确回传
        let callbackUrl =
          "http://tc.cupid.iqiyi.com/dsp_conversion_cb/special?ai=" +
          oaid +
          "&pf=" +
          platform +
          "&e=" +
          clientIp +
          "&et=" +
          timestamp;

        if (isPrecise) {
          callbackUrl = dbData.callbackurl.replace("__PAYMENT_AMOUNT__", "0");
        }
        const sendCallbackUrl = `${callbackUrl}&event_type=5`;
        return axios.get(sendCallbackUrl);
      })
    )
      .then((resp) => {
        console.log(resp);
        reqData.error.info.push({
          type: "首次回传成功",
          detail: "用户首次进入回传成功 (type = 5)",
          content: JSON.stringify(resp.response?.data || resp.data || resp),
          oaid,
          platform
        });
        console.log("首次进入回传成功 type = 5");
      })
      .catch((error) => {
        reqData.error.info.push({
          type: "首次回传失败",
          detail: "用户首次进入回传失败 (type = 5)",
          content: JSON.stringify(error.response?.data || error),
          oaid,
          platform
        });
      });
  }

  req.data = reqData;
  next();
}

// 用于记录数据的主处理程序
async function handleLogRequest(req, res) {
  const reqData = req.data;
  const bodyData = req.body;
  try {
    if (!bodyData || !bodyData.oaid) {
      return sendResponse(res, 400, null, "缺少 oaid");
    }
    // 首次进入递增 enter 计数
    if (reqData.firstEnter) {
      reqData.enter = Number(reqData.enter) + 1;
    }
    reqData.enter = Number(reqData.enter) || 1;

    // 统一数值类型，并保证数据结构存在
    const banner = Number(bodyData.banner) || 0;
    const video = Number(bodyData.video) || 0;
    const interstitial = Number(bodyData.interstitial) || 0;
    reqData.data = reqData.data || { fake: {} };
    reqData.data.fake = reqData.data.fake || {};
    reqData.data.fake[reqData.enter] = {
      enter: reqData.enter,
      time: new Date().toLocaleString(),
      num: {
        banner,
        video,
        interstitial
      }
    };

    await db.dbQuery(
      "UPDATE log1 SET banner = ?, video = ?, interstitial = ?, data = ?, enter = ?, error = ?, create_at = now() WHERE oaid = ?",
      [
        banner,
        video,
        interstitial,
        JSON.stringify(reqData.data),
        reqData.enter,
        JSON.stringify(reqData.error),
        bodyData.oaid
      ]
    );

    sendResponse(res, 200, {}, "success");
  } catch (error) {
    console.log("post log1 handleLogrequest error", error);
    logger.error(`路由 init/log处理程序出错: ${error}`);
    sendResponse(res, 500, null, "Internal Server Error");
  }
}

// 处理日志记录逻辑
router.post("/log", handleFirstEnter, handleLogRequest);

// 获取分页日志
router.get("/log", async (req, res) => {
  try {
    // 获取查询参数
    const { page = 1, page_size = 10, oaid, start_date, end_date } = req.query;
    const pageSize = parseInt(page_size, 10);
    const pageNum = parseInt(page, 10);
    const offset = (pageNum - 1) * pageSize;

    // 辅助：规范化日期参数
    function normalizeDateParam(dateStr, isEnd) {
      if (!dateStr) return null;
      const yyyyMmDd = /^\d{4}-\d{2}-\d{2}$/;
      if (yyyyMmDd.test(dateStr)) {
        return isEnd ? `${dateStr} 23:59:59` : `${dateStr} 00:00:00`;
      }
      const d = new Date(dateStr);
      if (!isNaN(d)) {
        const pad = (n) => String(n).padStart(2, "0");
        const y = d.getFullYear();
        const m = pad(d.getMonth() + 1);
        const day = pad(d.getDate());
        const hh = pad(d.getHours());
        const mm = pad(d.getMinutes());
        const ss = pad(d.getSeconds());
        return `${y}-${m}-${day} ${hh}:${mm}:${ss}`;
      }
      return null;
    }

    const conditions = [];
    const queryParams = [];
    const countParams = [];

    if (oaid) {
      conditions.push("oaid = ?");
      queryParams.push(oaid);
      countParams.push(oaid);
    }

    const sd = normalizeDateParam(start_date, false);
    if (sd) {
      conditions.push("create_at >= ?");
      queryParams.push(sd);
      countParams.push(sd);
    }

    const ed = normalizeDateParam(end_date, true);
    if (ed) {
      conditions.push("create_at <= ?");
      queryParams.push(ed);
      countParams.push(ed);
    }

    const whereClause = conditions.length
      ? " WHERE " + conditions.join(" AND ")
      : "";

    // 汇总统计（enter / track 总和）
    // 统计 enter 总和、track 值为 1 的行数、track 值为 0 的行数，以及 track 的数值总和（如有需要）
    //   const aggQuery = `
    //    SELECT
    //      SUM(COALESCE(enter,0)) AS total_enter,
    //      SUM(COALESCE(track,0)) AS total_track_sum,
    //      SUM(CASE WHEN track = 1 THEN 1 ELSE 0 END) AS total_track_1,
    //      SUM(CASE WHEN track = 0 THEN 1 ELSE 0 END) AS total_track_0
    //    FROM log1
    //    ${whereClause}
    //  `;
    //   const [aggResult] = await db.dbQuery(aggQuery, queryParams);

    // 查询分页数据
    const dataQuery = `SELECT * FROM log1${whereClause} ORDER BY create_at DESC LIMIT ? OFFSET ?`;
    const countQuery = `SELECT COUNT(*) AS total FROM log1${whereClause}`;

    const logArr = await db.dbQuery(dataQuery, [
      ...queryParams,
      pageSize,
      offset
    ]);
    const [totalResult] = await db.dbQuery(countQuery, countParams);

    // 格式化时间
    const formattedLogs = (logArr || []).map((e) => ({
      ...e,
      create_at: new Date(e.create_at).toLocaleString()
    }));

    sendResponse(res, 200, {
      data: formattedLogs,
      total: totalResult.total,
      page: pageNum,
      pageSize: pageSize,
      totalPages: Math.ceil(totalResult.total / pageSize),
      hasNext: pageNum < Math.ceil(totalResult.total / pageSize)
      // totals: {
      //   enter: Number(aggResult?.total_enter) || 0,
      //   track: Number(aggResult?.total_track) || 0,
      //   track1: Number(aggResult?.total_track_1) || 0,
      //   track0: Number(aggResult?.total_track_0) || 0
      // }
    });
  } catch (error) {
    logger.error(`获取日志时出错: ${error}`);
    sendResponse(res, 500, null, "Internal Server Error");
  }
});

// 按 platform 统计 enter 总数（可选按时间区间过滤）
// 示例：/log/platform-stats?start_date=2025-11-01&end_date=2025-11-30
router.get("/log/platform-stats", async (req, res) => {
  try {
    const { start_date, end_date } = req.query;

    function normalizeDateParam(dateStr, isEnd) {
      if (!dateStr) return null;
      const yyyyMmDd = /^\d{4}-\d{2}-\d{2}$/;
      if (yyyyMmDd.test(dateStr)) {
        return isEnd ? `${dateStr} 23:59:59` : `${dateStr} 00:00:00`;
      }
      const d = new Date(dateStr);
      if (!isNaN(d)) {
        const pad = (n) => String(n).padStart(2, "0");
        const y = d.getFullYear();
        const m = pad(d.getMonth() + 1);
        const day = pad(d.getDate());
        const hh = pad(d.getHours());
        const mm = pad(d.getMinutes());
        const ss = pad(d.getSeconds());
        return `${y}-${m}-${day} ${hh}:${mm}:${ss}`;
      }
      return null;
    }

    const conditions = [];
    const params = [];

    const sd = normalizeDateParam(start_date, false);
    if (sd) {
      conditions.push("create_at >= ?");
      params.push(sd);
    }
    const ed = normalizeDateParam(end_date, true);
    if (ed) {
      conditions.push("create_at <= ?");
      params.push(ed);
    }

    const whereClause = conditions.length
      ? " WHERE " + conditions.join(" AND ")
      : "";

    const statsQuery = `
      SELECT
        platform,
        SUM(COALESCE(enter,0)) AS enter_total,
        SUM(CASE WHEN track = 1 THEN 1 ELSE 0 END) AS track_1_count,
        SUM(CASE WHEN track = 0 THEN 1 ELSE 0 END) AS track_0_count,
        COUNT(*) AS records
      FROM log1
      ${whereClause}
      GROUP BY platform
      ORDER BY enter_total DESC
    `;

    const rows = await db.dbQuery(statsQuery, params);

    // 全局汇总（与按 platform 分开的 totals）
    const totalsQuery = `
      SELECT
        SUM(COALESCE(enter,0)) AS total_enter,
        SUM(CASE WHEN track = 1 THEN 1 ELSE 0 END) AS total_track_1,
        SUM(CASE WHEN track = 0 THEN 1 ELSE 0 END) AS total_track_0
      FROM log1
      ${whereClause}
    `;
    const [totalsRow] = await db.dbQuery(totalsQuery, params);

    const stats = (rows || []).map((r) => ({
      platform: r.platform,
      enterTotal: Number(r.enter_total) || 0,
      records: Number(r.records) || 0
    }));
    const totals = {
      enterTotal: Number(totalsRow?.total_enter) || 0,
      track1: Number(totalsRow?.total_track_1) || 0,
      track0: Number(totalsRow?.total_track_0) || 0
    };

    sendResponse(res, 200, { stats, totals });
  } catch (error) {
    logger.error(`获取 platform 统计时出错: ${error}`);
    sendResponse(res, 500, null, "Internal Server Error");
  }
});

module.exports = router;
